const express = require("express");
const router = express.Router();
const axios = require("axios");
const { sequelize, User, Order } = require("../models");
const { success, failure } = require("../utils/responses");
const { BadRequest, NotFound } = require("http-errors");
const jwt = require("jsonwebtoken");
const { v4: uuidv4 } = require("uuid");
const userAuth = require("../middlewares/user-auth");
const logger = require("../utils/logger");
const moment = require("moment");

/**
 * 微信小程序登录
 * POST /wechat/sign_in
 */
router.post("/sign_in", async (req, res) => {
  try {
    const { code } = req.body;

    if (!code) {
      throw new BadRequest("请提供微信登录 code");
    }
    const appid = process.env.WECHAT_APPID;
    const secret = process.env.WECHAT_SECRET;
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`;
    const response = await axios.get(url);
    const { errcode, errmsg, openid } = response.data;

    if (errcode) {
      throw new BadRequest("微信登录失败：" + errmsg);
    }

    const user = await User.findOne({ where: { openid } });
    if (!user) {
      throw new NotFound("用户不存在");
    }

    success(res, "登录成功。", { openid });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
